<template>
  <div class="main">
    <span class="titl">应用名称:</span>
    <div class="input">
      <a-input v-model:value="name" placeholder="请输入应用名称" />
    </div>
    <span class="titl">访问链接:</span>
    <div class="input">
      <a-input v-model:value="url" placeholder="请输入正确链接" />
    </div>
    <span class="titl">上传图标:</span>
    <div class="upload">
      <a-upload name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false" :beforeUpload="beforeUpload">
        <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="100" />
        <div v-else>
          <plus-outlined></plus-outlined>
          <div class="ant-upload-text">Upload</div>
        </div>
      </a-upload>
    </div>
    <a-button type="primary" html-type="submit" :disabled="url === '' || imageUrl === ''|| name===''" @click="onClickUpload">
      提交
    </a-button>
  </div>
</template>

<script lang='ts'>
import { ref } from "vue";
import {
  LoadingOutlined,
  PlusOutlined,
} from "@/components/AntDesign/icons/icons";
import { $message } from "@/components/AntDesign/message";
import { upmmiao } from "@/api/miaoApi/index";
import $router from "@/router";

function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

export default {
  components: {
    LoadingOutlined,
    PlusOutlined,
  },
  setup() {
    const url = ref<string>("");
    const name = ref<string>("");
    const imageUrl = ref<string>("");
    let imgUrl = "";

    const beforeUpload = (file: any) => {
      getBase64(file, (base64Url: string) => {
        imageUrl.value = base64Url;
        imgUrl = base64Url.replace(/^data:image\/\w+;base64,/, "");
      });
      return false;
    };

    const onClickUpload = async () => {
      if (!/[a-zA-z]+:\/\/[^\s]*/.test(url.value))
        $message("error", "访问链接不规范");

      try {
        
        await upmmiao({
          name: name.value,
          url: url.value,
          img: imgUrl,
        });

        $message("success", "提交成功");
        $router.push({ path: "/miaolist" });

      } catch (error) {
        $message("error", "提交失败");
      }
    };

    return {
      name,
      url,
      beforeUpload,
      imageUrl,
      onClickUpload,
    };
  },
};
</script>
<style lang="less" scoped>
.main {
  width: 400px;
  margin: 100px auto;
  .titl {
    display: block;
    margin-bottom: 10px;
  }
  .input,
  .upload {
    margin-bottom: 40px;
  }
  .ant-btn {
    display: block;
    margin: 0 auto;
    width: 250px;
    height: 40px;
  }
}
</style>